using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Timers;
using InstantMessenger.Properties;
using TweetSharp;

namespace InstantMessenger.Transports
{
    public class TwitterTransport : ITransport
    {
        private const string ConsumerKey = "hNE7y7UvxWuONcv2lAo0A";
        private const string ConsumerSecret = "bp1aSqrmR4MZQPlDkI9MhQ8r63cYIldlhk8MiRnZm4";

        private readonly TwitterSettings twitterSettings;
        private readonly IDictionary<string, Contact> contacts = new Dictionary<string, Contact>();
        private readonly IList<Contact> twitterContacts = new List<Contact>();
        private Timer timer2;

        public TwitterTransport(TwitterSettings twitterSettings)
        {
            this.twitterSettings = twitterSettings;
        }

        public string DisplayName { get { return "Twitter"; } }

        public void Start(IEnumerable<Contact> allContacts)
        {
            foreach (var contact in allContacts)
            {
                contacts.Add(contact.Name, contact);
                if (twitterSettings.IsTwitterContact(contact.Name))
                    twitterContacts.Add(contact);
            }

            timer2 = new Timer
                         {
                             AutoReset = true,
                             Enabled = true,
                             Interval = new TimeSpan(0, 0, 30).TotalMilliseconds
                         };
            timer2.Elapsed += PollForNewMessages;
            timer2.Start();
        }

        public void Stop()
        {
            timer2.Stop();
            timer2.Dispose();
        }

        public bool DeliverMessage(string sender, string recipient, string message)
        {
            var senderTwitterContact = twitterSettings.GetTwitterContact(sender);
            var recipientTwitterContact = twitterSettings.GetTwitterContact(recipient);

            var service = new TwitterService(ConsumerKey, ConsumerSecret);

            service.AuthenticateWith(senderTwitterContact.AccessToken, senderTwitterContact.AccessTokenSecret);
            service.SendDirectMessage(recipientTwitterContact.TwitterUserName, message);

            return true;
        }

        private void PollForNewMessages(object state, ElapsedEventArgs elapsedEventArgs)
        {
            foreach (var contact in contacts.Values.Where(c => c.IsOnline))
            {
                var twitterContact = twitterSettings.GetTwitterContact(contact.Name);
                if (twitterContact == null || !twitterContact.CanRead) continue;

                var service = new TwitterService(ConsumerKey, ConsumerSecret);
                service.AuthenticateWith(twitterContact.AccessToken, twitterContact.AccessTokenSecret);
                var directMessages = service.ListDirectMessagesReceivedSince(twitterContact.LastDirectMessageId);

                foreach (var directMessage in directMessages ?? Enumerable.Empty<TwitterDirectMessage>())
                {
                    var message = directMessage;
                    twitterContact.LastDirectMessageId = directMessage.Id;

                    var senderContact = GetContact(message.SenderScreenName);
                    if (senderContact != null)
                        contact.DeliverMessage(senderContact, directMessage.Text);
                }

            }

            // Yuck
            Settings.Default.Save();
        }

        private Contact GetContact(string senderTwitterName)
        {
            return (from contact in twitterContacts
                    where twitterSettings.GetTwitterContact(contact.Name).TwitterUserName == senderTwitterName
                    select contact).FirstOrDefault();
        }

        public bool IsOnline(Contact contact)
        {
            return true;
        }

        public void AddContact(Contact contact)
        {
            // TODO: What do we do here?
        }

        public void RemoveContact(Contact contact)
        {
            // TODO: What do we do here?
        }

        public static OAuthRequestToken StartAuthorise()
        {
            var service = new TwitterService(ConsumerKey, ConsumerSecret);
            var requestToken = service.GetRequestToken();
            var uri = service.GetAuthorizationUri(requestToken);
            Process.Start(uri.ToString());
            return requestToken;
        }

        public static OAuthAccessToken EndAuthorise(OAuthRequestToken requestToken, string verifier)
        {
            var service = new TwitterService(ConsumerKey, ConsumerSecret);
            return service.GetAccessToken(requestToken, verifier);
        }
    }
}